package com.kun.service.handle;

import com.kun.utils.AjaxResult;
import com.kun.utils.JsonUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {


    private static void sendRespose(HttpServletResponse response, HttpStatus httpStatus, String message) throws IOException {
        response.setStatus(httpStatus.value());
        response.setContentType("application/json;charset=UTF-8");
        ResponseEntity<AjaxResult> response1 = AjaxResult.error(httpStatus, message);
        response.getWriter().write(JsonUtils.toJson(response1.getBody()));
    }

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {
        sendRespose(response, HttpStatus.BAD_REQUEST, accessDeniedException.getMessage());
    }
}
